package com.ruoyi.lzxt.user.service;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.dto.RoleDTO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.service.LogininforService;
import com.ruoyi.common.enums.DeviceType;
import com.ruoyi.common.enums.LoginType;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.lzxt.user.domain.entity.Employee;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequiredArgsConstructor
@Slf4j
@Service
public class LoginService {
    @Value("${user.password.maxRetryCount}")
    private Integer maxRetryCount;

    @Value("${user.password.lockTime}")
    private Integer lockTime;

    private final EmployeeService userService;

    private final LogininforService asyncService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        HttpServletRequest request = ServletUtils.getRequest();
        Employee user = loadUserByUsername(username);
        //checkLogin(LoginType.PASSWORD, username, () -> !BCrypt.checkpw(password, user.getPassword()));
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        LoginUser loginUser = buildLoginUser(user);
        // 生成token
        LoginHelper.loginByDevice(loginUser, DeviceType.PC);

        asyncService.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"), request);
        // 用户表中更新用户最后登录时间，ip
        //recordLoginInfo(user.getUser_Id(), username);
        return StpUtil.getTokenValue();
    }

    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    private Employee loadUserByUsername(String username) {
        Employee user = userService.selectUserByUserName(username);
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UserException("user.not.exists", username);
        } else if ("1".equals(user.getPara5())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new UserException("user.password.delete", username);
        } else if ("1".equals(user.getIsForbidden())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new UserException("user.blocked", username);
        }
        return user;
    }

    /**
     * 构建登录LoginUser
     * @param user
     * @return
     */
    private LoginUser buildLoginUser(Employee user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setLzUserId(user.getUserGUID());
        //loginUser.setDeptId(user.getDeptId());
        loginUser.setUsername(user.getUserId());
        loginUser.setUserType("lz_user"+user.getJobPostName());
        //loginUser.setMenuPermission(permissionService.getMenuPermission(user));
        //loginUser.setRolePermission(permissionService.getRolePermission(user));
        loginUser.setDeptName(ObjectUtil.isNull(user.getDepartmentName()) ? "" : user.getDepartmentName());
        //List<RoleDTO> roles = BeanUtil.copyToList(user.getRoles(), RoleDTO.class);
        //loginUser.setRoles(roles);
        return loginUser;
    }
    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    // 未实现
//    public void recordLoginInfo(Long userId, String username) {
//        SysUser sysUser = new SysUser();
//        sysUser.setUserId(userId);
//        sysUser.setLoginIp(ServletUtils.getClientIP());
//        sysUser.setLoginDate(DateUtils.getNowDate());
//        sysUser.setUpdateBy(username);
//        userService.updateUserProfile(sysUser);
//    }
}
